<?
if (!defined('SMF'))
	die('Hacking attempt...');

global $doomsday_value, $space_plague_kills;

$doomsday = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_planets}
	WHERE colonists > {int:doomsday_value}',
	array(
		'db_planets' => $dbtables['planets'],
		'doomsday_value' => $doomsday_value
	)
);
							
$chance = 9;
$reccount = $smcFunc['db_num_rows']($doomsday);

// Increase chance it will happen if we have lots of planets meeting the criteria.
if ($reccount > 200)
	$chance = 7; 

// Run the apocalypse mechanism a certain number of times based on the current multiplier
for ($cycles = 1; $cycles <= $multiplier; $cycles++)
{
	// The chance something bad will happen.
	$affliction = rand(1,$chance);

	if ($affliction < 3 && $reccount > 0)
	{
		$i = 1;
		$targetnum = rand(1,$reccount);
		
		while ($smcFunc['db_num_rows']($doomsday) > 0)
		{
			if ($i == $targetnum)
			{
				$targetinfo = $smcFunc['db_fetch_assoc']($doomsday);
				break;
			}
			$i++;
		}
		
		// Reset data pointer to the beginning of the result in case there are multiple cycles
		$smcFunc['db_data_seek']($doomsday, 0);
		
		// Space plague.
		if ($affliction == 1)
		{
			$message .= 'The horsemen release the Space Plague!<br>.';
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET colonists = ROUND(colonists - colonists * {float:space_plague_kills})
				WHERE planet_id = {int:planet_id}',
				array(
					'db_planets' => $dbtables['planets'],
					'space_plague_kills' => $space_plague_kills,
					'planet_id' => $targetinfo['planet_id']
				)
			);
			
			$logpercent = ROUND($space_plague_kills * 100);
			playerlog($targetinfo['owner'],LOG_SPACE_PLAGUE,"$targetinfo[name]|$targetinfo[sector_id]|$logpercent"); 
		}
		else
		{
			$message .= 'The horsemen release a Plasma Storm!<br>.';
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET energy = 0
				WHERE planet_id = {int:planet_id}',
				array(
					'db_planets' => $dbtables['planets'],
					'planet_id' => $targetinfo['planet_id']
				)
			);
			playerlog($targetinfo['owner'],LOG_PLASMA_STORM,"$targetinfo[name]|$targetinfo[sector_id]");
		}
	}
}

$smcFunc['db_free_result']($doomsday);	
?>
